﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;


namespace UIFramwork
{
    /// <summary>
    /// UI 资产类
    /// </summary>
    public class UIAssets
    {
        /// <summary>
        /// 资产目录
        /// </summary>
        public Dictionary<Type, GameObject> UIAssetsLib;


        public UIAssets()
        {
            UIAssetsLib = new Dictionary<Type, GameObject>();
        }


        /// <summary>
        /// 获取|资产
        /// </summary>
        public bool TryGetUIAsset(Type type, out GameObject output)
        { 
            bool isGet = UIAssetsLib.TryGetValue(type, out output);
            if (isGet)
            {
                return true;
            }

            return TryLoadUIAsset(type, out output);
        }

        /// <summary>
        /// 加载|资产
        /// </summary>
        private bool TryLoadUIAsset(Type type, out GameObject output)
        {
            if (type.GetCustomAttributes(false)
                .ToList()
                .Find(e => e is UIDetailAttribute) is not UIDetailAttribute match)
            {
                Debug.LogError($"UIAssets|获取类绑定资产路径失败，请检查类！|{type}");
                output = null;
                return false;
            }

            Debug.Log($"UIAssets|{type.Name}|加载路径：{match.ResourcePath}");
            output = Resources.Load(match.ResourcePath) as GameObject;

            // 检查 资产是否合格
            bool isHasUIBase = output.TryGetComponent(out UIBase ui);
            if (!isHasUIBase)
            {
                Debug.LogWarning($"UIAssetsPool|资产类未继承UIBase，初始化失败！|{type}");
                output = null;
                return false;
            }

            UIAssetsLib.Add(type, output);

            return true;
        }
    }
}